package com.yojcodesendbox;

import java.io.*;

public class CompileAndRunCpp {
    public static void main(String[] args) {
        try {
            String rootDir = System.getProperty("user.dir");

            System.out.println();
            // 编译C++程序
            Process compileProcess = Runtime.getRuntime().exec("g++ -o HelloWorld " + rootDir + File.separator + "tempCode" + File.separator + "HelloWorld.cpp");
            // 等待编译过程结束
            compileProcess.waitFor();
            if (compileProcess.exitValue() != 0) {
                InputStream errorStream = compileProcess.getErrorStream();
                InputStreamReader isrError = new InputStreamReader(errorStream);
                BufferedReader brError = new BufferedReader(isrError);
                String lineError;
                boolean hasError = false;
                while ((lineError = brError.readLine()) != null) {
                    System.out.println("Error: " + lineError);
                    hasError = true;
                }
                System.out.println("Compilation failed.");
                return;
            }

            // 执行编译后的程序
            Process runProcess = Runtime.getRuntime().exec("./HelloWorld");
            // 读取执行结果
            InputStream is = runProcess.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            // 等待执行过程结束
            runProcess.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}